package cn.kgc.vue.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.service.TemplateService;
import cn.kgc.vue.mapper.TemplateMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
* @author mengshun
* @description 针对表【sys_template】的数据库操作Service实现
* @createDate 2024-04-17 10:31:01
*/
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService{


    @Override
    public ResponseResult resourcesPage(QueryCondition<Template> queryCondition) {

        Page<Template> templatePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        String fileName = queryCondition.getSearchParams().getFileName();

        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(StringUtils.isNotBlank(fileName),Template::getFileName,fileName)
                .orderByDesc(Template::getCreateTime);

        baseMapper.selectPage(templatePage,lambda);
        return ResponseResult.success()
                .data("total",templatePage.getTotal())
                .data("tableData",templatePage.getRecords());
    }

    @Override
    public ResponseResult upload(MultipartFile file) {

        if (file.isEmpty()){
            ResponseResult.fail().message("请选择文件");
        }

        // 处理文件的名字  唯一
        String originalFilename = file.getOriginalFilename();
        // 获取文件大小
        double size = file.getSize()/1000.0;
        // 获取文件的扩展名   png  doc
        String filenameExtension = org.springframework.util.StringUtils.getFilenameExtension(originalFilename);
        String uuid = IdUtil.simpleUUID();
        String uuidName = uuid+"."+filenameExtension;

        // 上传文件到服务器指定的目录
        File file1 = new File("D:/upload/springboot");
        if (!file1.exists()){
            file1.mkdir();
        }

        File file2 = new File(file1, uuidName);

        try {
            file.transferTo(file2);
        } catch (IOException e) {
            return  ResponseResult.fail().message("文件上传失败");
        }
        return ResponseResult.success()
                .data("uuidName",uuidName)
                .data("size",size);
    }
}




